package com.easyaop.asm.bytecode;

import lombok.Getter;
import org.objectweb.asm.Type;

import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Getter
public class MethodInfo {

    public int access;
    public String name;
    public String descriptor;
    public String signature;
    public String[] exceptions;

    public Type[] ptypes;
    private List<Object> text;

    public int maxLocal;

    public MethodInfo(int access, String name, String descriptor, String signature, String[] exceptions
            , List<Object> text
    ) {
        this.access = access;
        this.name = name;
        this.descriptor = descriptor;
        this.signature = signature;
        this.exceptions = exceptions;
        this.text = text;

        this.ptypes = Type.getArgumentTypes(descriptor);
    }

    private static String to(List list) {
        return (String) list.stream()
                .map(a -> (a instanceof List) ? to((List) a) : a.toString())

                .collect(Collectors.joining("\n"));
    }

    public String getBody() {
        return to(text);
    }

    // 入参的size（包括this）
    public int argSize() {
        return Arrays.stream(Type.getArgumentTypes(descriptor)).mapToInt(Type::getSize).sum()
                + (Modifier.isStatic(access) ? 0 : 1)
                ;
    }
}
